package com.caiwangdai.app.extension

import android.content.Context
import android.text.TextUtils
import com.caiwangdai.app.BuildConfig
import com.caiwangdai.app.bean.UserB
import com.google.gson.Gson


val SHAREAPP = "share_app"
val SHAREPERSON = "share_USER"

//fun Context.clearAppShare() {
//    val sp = AppData.context.getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
//    sp.edit().remove(SHAREAPP).apply()
//}
//
//private fun Context.setAppShare(share: AppSharePreB) {
//    val sp = getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
//    sp.edit().putString(SHAREAPP, share.toJson()).apply()
//}
//
//fun Context.getAppShare(): AppSharePreB {
//    val sp = getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
//    val infoString = sp.getString(SHAREAPP, "")
//    if (infoString.isEmpty()) {
//        val apShare = AppSharePreB()
//        setAppShare(apShare)
//        return apShare
//    }
//    return Gson().fromJson<AppSharePreB>(infoString, AppSharePreB::class.java)
//}
//
////存储某些变量
//fun Context.saveShareStuff(fn: AppSharePreB.() -> Unit) {
//    val appSharePre = getAppShare()
//    appSharePre.fn()
//    setAppShare(appSharePre)
//}


//用户操作

//注销
private fun Context.clearUser() {
    val sp = getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
    sp.edit().remove(SHAREPERSON).apply()
}


private fun Context.setUser(user: UserB?) {
    var sp = getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
    sp.edit().putString(SHAREPERSON, user?.toJson()).apply()
}

fun Context.getUser(): UserB? {
    val sp = getSharedPreferences(BuildConfig.APPNAME, Context.MODE_PRIVATE)
    val infoString = sp.getString(SHAREPERSON, "")
    if (TextUtils.isEmpty(infoString)) {
        return null
    }
    return Gson().fromJson<UserB>(infoString, UserB::class.java)
}

//登出
fun Context.logOut() {
    clearUser()
}

fun Context.logIn(user: UserB?) {
    setUser(user)
}

//是否已经登录
fun Context.isUserLogined(): Boolean {
    return getUser() != null
}

